<?php
namespace app\index\controller;
use app\classes\helper\BehaviorRedis;
use app\index\model\Popup as pop;
use app\index\server\ContentServer;
use think\Controller;
use think\Db;
use think\facade\Request;
class Popup extends Controller
{
    protected $middleware = ['VerifyLogin'];

    /**
     * 获取弹窗
     * @return \think\response\Json
     */
    public function getPop()
    {
        $seat = input('seat');
        if (!in_array($seat, [1, 2, 3, 4, 5, 6, 7])) {
            return json(['code'=>101,'msg'=>'弹窗位置不存在']);
        }
        //不是白名单 && （没有归属 || 黑名单 || 审核人员）
        $checkIpBlackResult = checkIpBlackByToken();
        if($checkIpBlackResult['status'] == true)
        {
            return json(['code'=>101,'msg'=>'弹窗推送获取失败']);
        }

        if ($seat == 1) {
            $current_time = time(); // 获取当前时间戳
            $two_minutes_ago = $current_time - 120; // 120秒等于两分钟
            $start_time = strtotime(date('Y-m-d H:i:s', $two_minutes_ago));
            $oWhere = [];
            $oWhere[] = ['uid', '=', request()->userInfo['id']];
            $oWhere[] = ['status', '=', 1];
            $oWhere[] = ['create_time', '>=', $start_time];
            $id = Db::table("quick_user")->where($start_time)->value("id");
            if (!$id) {
                return json(['code'=>101,'msg'=>'弹窗推送获取为空']);
            }
        }
        //弹出日期判断
        $weekDay = date('w');
        $dayWhere = "";
        $today = date("Y-m-d");
        if ($weekDay == 6){
            $dayWhere = "`date_type` IN ( 1, 2, 4 ) OR (`date_type` = 5 AND `end_date` >= '{$today}' AND `start_date` <= '{$today}')";
        }elseif ($weekDay == 0){
            $dayWhere = "`date_type` IN ( 1, 3, 4 ) OR (`date_type` = 5 AND `end_date` >= '{$today}' AND `start_date` <= '{$today}')";
        }

        $user = request()->userInfo;
        if ($user['agent_id']) {
            $where[] = ['manager_id', 'in', [0, $user['agent_id']]];
        } else {
            $where[] = ['manager_id', '=', 0];
        }

        $quickAppId = request()->quickAppId;

        /**弹窗位置*/
        $where[] = ['', 'exp', Db::raw("FIND_IN_SET($seat,seat)")];
        /**快应用*/
        $where[] = ['status', '=', 1];
        $where[] = ['', 'exp', Db::raw("FIND_IN_SET($quickAppId,quick_apps)")];
        /**用户群体*/
        $map1[] = ['test_user_id', '=', $user['id']];
        $map2[] = ['user_grep', '=', 1];

        /**充值条件*/
        $pur = Db::table("quick_pay_user_record")->where("uid",$user['id'])->field("id,pay_money,pay_num")->find();
        if ($pur) {
            $map2[] = ['is_pay', 'in', [0, 1]];
        } else {
            $map2[] = ['is_pay', 'in', [0, 2]];
        }

        $query = Pop::where($dayWhere)->where($where)->where(function ($query) use ($map1, $map2) {
            $query->whereOr([$map1, $map2]);
        });

        $query = $query->where(function ($query) use ($user) {
            $agent_id = $user['agent_id'];
            if ($user['agent_id']) {
                $where1[] = ['', 'exp', Db::raw("FIND_IN_SET($agent_id,agents)")];
                $where1[] = ['type', '=', 3];
                $where2[] = ['type', '<>', 3];
                $query->whereOr([$where1, $where2]);
            }
        });

        $list = $query->order("topped desc,wgt desc,id desc")->select();
        $pop = null;
        $now = time();
        $suffix = date("Ym");
        foreach ($list as $k => $v) {
            if ($v['test_user_id'] != $user['id']) {
                if ($v['is_pay'] == 1) {
                    if (!$pur) {
                        continue;
                    } elseif ($pur['pay_money'] < $v['mini_pay_money']) {
                        continue;
                    } elseif ($pur['pay_num'] < $v['mini_pay_num']) {
                        continue;
                    }
                }
                if ($v['register_type'] == 1) {
                    $regtime = strtotime($user['regtime']);
                    $startTime = 0;
                    $endTime = INF;
                    if ($v['register_start']) {
                        $startTime = $regtime + ($v['register_start'] * 86400);
                    }
                    if ($v['register_end']) {
                        $endTime = $regtime + ($v['register_end'] * 86400);
                    }
                    if ($now < $startTime || $now > $endTime) {
                        continue;
                    }
                }
                //最低阅读章节
                if ($v['read_num'] > 0) {
                    $count = Db::table("quick_user_read_record_{$suffix}")->where("uid", $user['id'])->count();
                    if ($count < $v['read_num']) {
                        continue;
                    }
                }
            }
            $pop = $v;
            break;
        }
        if ($pop) {
            $res = $this->frequencyJudge($pop);
            if (!$res){
                return json(['code'=>101,'msg'=>'弹窗推送获取为空']);
            }
            $data['type'] = $pop['type'];
            if ($pop['type'] == 1) {
                //推书
                $novelWhere[] = ['id', 'in', $pop['novels']];
                $novelWhere[] = ['in_shelf', '=', 1];
                $filed = "id novel_id,cover,origin_title novel_title,author,freq_id,class_id,update_status,brief,number_words";
                $list = Db::table('novel')->where($novelWhere)->cache(6000)->field($filed)->select();
                $cidArr = array_column($list, 'class_id');
                $fidArr = array_column($list, 'freq_id');
                $classList = ContentServer::plGetNovelClass($cidArr);
                $freqList = ContentServer::plGetNovelFreq($fidArr);
                foreach ($list as $k => $v) {
                    $list[$k]['cover'] = config('img_domain') . $v['cover'];
                    $list[$k]['freq'] = isset($freqList[$v['freq_id']]) ? $freqList[$v['freq_id']] : '';
                    $list[$k]['novel_class'] = isset($classList[$v['class_id']]) ? $classList[$v['class_id']] : '';
                }
                $data['novels'] = $list;
            } elseif ($pop['type'] == 2) {
                //活动充值
                $data['pic'] = config('img_domain') . $pop['pic'];
                $data['activity_id'] = $pop['activity_id'];
            } else {
                //外部链接
                $data['pic'] = config('img_domain') . $pop['pic'];
                $data['jump_url'] = $pop['jump_url'];
            }

            return json(['code'=>0,'msg'=>'success','data'=>$data]);
        } else {
            return json(['code'=>101,'msg'=>'弹窗推送获取为空']);
        }
    }


    /**
     * 弹窗频率判断
     * @param $pop
     * @return bool
     */
    private function frequencyJudge($pop)
    {
        if ($pop['frequency'] != 0) {
            /**判断显示频率，如果未过期则不展示*/
            $behaviorRedis = new BehaviorRedis();
            $flag = $behaviorRedis->getPopLog($pop['id'], $pop['frequency'], request()->userInfo['id']);
            if ($flag) {
                return false;
            } else {
                if ($pop['frequency'] == 1) {
                    $expire = 86400;
                } elseif ($pop['frequency'] == 2) {
                    $expire = 3600;
                } elseif ($pop['frequency'] == 3) {
                    $expire = 7200;
                } elseif ($pop['frequency'] == 4) {
                    $expire = 21600;
                } elseif ($pop['frequency'] == 5) {
                    $expire = 28800;
                } else {
                    return false;
                }
                $behaviorRedis->addPopLog($pop['id'], $pop['frequency'], request()->userInfo['id'], $expire);
                return true;
            }
        }else{
            return true;
        }
    }

}